package edu.gdkm.interceptor;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.Set;

public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request.getSession().getAttribute("username")!=null){
            return true;
        }else{
            request.setAttribute("msg","你没有权限，请登录后再试!");
            request.getRequestDispatcher("/login.jsp").forward(request,response);
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ModelMap models =modelAndView.getModelMap();
        System.out.println("postHandle:"+models);
        for (String key: models.keySet()) {
            if(!key.contains("springframework")){                   //为了排除springmvc自动添加的对象校验
                ObjectMapper om =new ObjectMapper();                //jackson的核心操作类，可以将对象转成json字符串，也可能序列化json字符串为一个对象
                String value=om.writeValueAsString(models.get(key)); //对象转成json字符串

                value=value.replaceAll("清","*");    //替换掉json字符串中的"清"
                Object o=om.readValue(value,models.get(key).getClass()); //序列化json字符串为一个对象
                modelAndView.getModel().put(key,o);                      //将替换字符串之后的对象放回原key
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("----------------------------");
        System.out.println("interceptor afterCompletion");
        System.out.println(ex);
        System.out.println("----------------------------");
    }
}
